package org.monitor.servlet.pairs;

import java.util.HashMap;
import java.util.Map;

public class Pairs {
	
	private Map<String, String> pairMap;
	private Map<String, String> fileMap;
	private byte[] postData;
	
	public Pairs(){
		this.pairMap = new HashMap<String, String>();
		this.fileMap = new HashMap<String, String>();
	}
	
	public String getPair(String name){
		return pairMap.get(name);
	}
	
	public Map<String, String> getFiles(){
		return fileMap;
	}
	
	void addPair(String name, String value){
		this.pairMap.put(name, value);
	}
	
	void addFile(String filename, String filePath){
		this.fileMap.put(filename, filePath);
	}
	
	public byte[] getPostData() {
		return postData;
	}
	
	void setPostData(byte[] postData){
		this.postData = postData;
	}

	protected Pairs clone(){
		Pairs newPairs = new Pairs();
		newPairs.pairMap = (Map<String, String>) ((HashMap<String, String>)pairMap).clone();
		newPairs.fileMap = (Map<String, String>) ((HashMap<String, String>)fileMap).clone();
		newPairs.postData = postData != null ? postData.clone() : null;
		return newPairs;
	}
	
	public void checkRequired(String pair, String... otherPairs){
		StringBuilder sb = new StringBuilder();
		if(isEmpty(pair)){
			sb.append(pair).append(",");
		}
		if(otherPairs != null){
			for (String oPair : otherPairs) {
				if(isEmpty(oPair)){
					sb.append(oPair).append(",");
				}
			}
		}
		if(sb.length() != 0){
			throw new RuntimeException("缺少参数：" + sb.toString());
		}
	}
	
	private boolean isEmpty(String pair){
		String value = this.pairMap.get(pair);
		if(value == null || "".equals(value.trim())){
			return true;
		}
		return false;
	}
	
	public PairsBuilder copy(){
		return PairsBuilder.create(this);
	}
}
